import "./app.css";
import { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { add, del, checked, allChecked } from "./store/modules/taskStore";
import { v4 as uuid } from "uuid";
function App() {
  const { dataList } = useSelector(state => state.taskStore);
  const dispatch = useDispatch();
  const [value, setValue] = useState("");

  // 单选
  const onChange = id => {
    dispatch(checked(id));
  };
  // 全选
  const isAll = e => {
    dispatch(allChecked(e.target.checked));
  };
  // 添加
  const onKeyUp = e => {
    // 判断是否点击的是回车
    if (e.key === "Enter") {
      dispatch(
        add({
          id: uuid(),
          name: value,
          isDone: false,
        })
      );
      setValue("");
    }
  };
  return (
    <section className="todoapp">
      <header className="header">
        <h1>todos</h1>
        <input
          className="new-todo"
          autoFocus
          autoComplete="off"
          placeholder="What needs to be done?"
          onInput={e => setValue(e.target.value)}
          value={value}
          onKeyUp={onKeyUp}
        />
      </header>
      <section className="main">
        <input
          id="toggle-all"
          className="toggle-all"
          type="checkbox"
          checked={dataList.every(v => v.isDone)}
          onChange={isAll}
        />
        <label htmlFor="toggle-all"></label>
        <ul className="todo-list">
          {dataList.map(v => (
            <li className={v.isDone ? "completed todo" : "todo"} key={v.id}>
              <div className="view">
                <input
                  checked={v.isDone}
                  className="toggle"
                  type="checkbox"
                  onChange={() => onChange(v.id)}
                />
                <label>{v.name}</label>
                <button
                  className="destroy"
                  onClick={() => dispatch(del(v.id))}></button>
              </div>
            </li>
          ))}
        </ul>
      </section>
    </section>
  );
}

export default App;
